package fs.component.buttons {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.ColorMatrixFilter;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import fs.component.event.ComponentEvent;
	
	/**
	 * ...
	 * @author F.S.
	 */
	public class ToggleButton extends Sprite {
		
		private var _square:Sprite;
		private var _ticket:Sprite;
		private var _tfContent:TextField;
		
		private var _enabledLayer:Sprite;
				
		private var _isOn:Boolean;
		private var _isEnabled:Boolean = true;
		private var _title:String = "";
		
		public var onChanged:Function;
		
		public function ToggleButton() {
			addUi();
			addEvent();
		}
		
		private function addEvent():void {
			addEventListener(MouseEvent.CLICK, onClick);
		}
		
		private function onClick(e:MouseEvent):void {
			if (!_isEnabled) return;
			isOn = !isOn;
		}
		
		private function addUi():void {
			_enabledLayer = new Sprite();
			addChild(_enabledLayer);
			
			_square = new Sprite();
			_square.graphics.lineStyle(0.5);
			_square.graphics.beginFill(0xffffff);
			_square.graphics.drawRect(0, 5, 10, 10);
			_square.graphics.endFill();
			_enabledLayer.addChild(_square);
			
			_ticket = new Sprite();
			_ticket.graphics.lineStyle(2);
			//_ticket.graphics.beginFill(0);
			//_ticket.graphics.drawRect(2, 7,6,6);
			//_ticket.graphics.endFill();
			_ticket.graphics.moveTo(2, 9);
			_ticket.graphics.lineTo(5,14);
			_ticket.graphics.lineTo(15,4);
			_ticket.visible = false;
			_enabledLayer.addChild(_ticket);
			
			_tfContent = new TextField();
			_tfContent.x = 12;
			_tfContent.autoSize = TextFieldAutoSize.LEFT;
			_tfContent.selectable = false;
			_enabledLayer.addChild(_tfContent);
			
			buttonMode = true;
		}
		
		public function get isOn():Boolean {
			return _isOn;
		}
		
		public function set isOn(value:Boolean):void {
			_ticket.visible = value;
			
			if (_isOn != value ) {
				_isOn = value;
				if (null != onChanged) {
					var event:ComponentEvent = new ComponentEvent(Event.CHANGE,this);
					onChanged.apply(null, [event]);
				}
			}
		}
		
		public function get isEnabled():Boolean {
			return _isEnabled;
		}
		
		public function set isEnabled(value:Boolean):void {
			_enabledLayer.filters = value?[]:[new ColorMatrixFilter([1,  0,  0, 0,0x80,
																	 0,  1,  0, 0,0x80,
																	 0,    0,1, 0,0x80,
																	 0,    0,  0, 1,0 ])];
			_isEnabled = value;
		}
		
		public function get title():String {
			return _title;
		}
		
		public function set title(value:String):void {
			_title = value;
			_tfContent.text = title;
		}
	}

}